import { reactive, ref, computed } from "vue";
import router from "../../router/index";
import { queryArticle,hotInformation } from "../../service/article/";
import { getHomeHotData, getBannerData } from "../../service/home"
import { useSearchStore } from "../../store/search";
import { useUserStore } from "../../store/user"
import jsCookie from "js-cookie"
import { zlDialog } from "../../utils/zlDialog"
import {hightLight} from '../../utils/index'
import { debounce, throttle } from 'lodash';

const searchStore = useSearchStore()

export const useHomeHooks = () => {
  const userStore = useUserStore()

  // 获取权限
  userStore.updateUserAuth()

  // 权限限制
  const auth = computed<any>(() => userStore.auth)

  // 获取用户信息
  userStore.getUserInfo()
  const userInfo = computed<any>(() => userStore.userInfo)

  const vipType = computed<any>(() => userInfo.value.vip)

  const dataTotal = ref(0)

  const loading = ref(true)

  const pageInfo = reactive({
    pageNum: 1,
    pageSize: 10
  });

  const searchTypeInfos = ref([
    { name: "资讯", unit: "条" },
    { name: "政策", unit: "类" },
    { name: "部门", unit: "个" },
    { name: "立项数据", unit: "条" },
  ])

  const dataList = ref<any[]>([]);
  const hotRepInformationList = ref<any[]>([]);
  const hotResInformationList = ref<any[]>([]);

  // 首页数据分页方法
  const pageInfoChange = (e: any) => {
    // 超过可查看限制直接返回false
    let limitCount = auth.value.itemCount;
    // if (pageInfo.pageNum * pageInfo.pageSize - pageInfo.pageSize >= limitCount) {
    //   pageInfo.pageNum = Math.ceil(limitCount / pageInfo.pageSize)
    // }
    query(queryParams.value)
  };

  const handleCardClick = (id: string) => {
    router.push({ path: "/detail", query: { id } });
  };

  /**
   * 搜索方法
   */
  const queryParams = ref<any>()

  // 首次进入搜索默认热点数据
  getHomeHotData(searchStore.searchType).then((res: any) => {
    console.log(res);

  })
  const gather = ref('')

  const getDepHomeData = (params)=>{
    gather.value =params.itemGrade
    queryArticle(params,{ pageNum: 1, pageSize: 10 }).then(res=>{
      dataList.value = res.rows
      dataTotal.value = res.total
    })
  }

  const newsData = ref<any[]>([])
  const enterSearchTypeByFourCount = ref<number>(0)

  const query = throttle(async (params: any, isRest = true,page = pageInfo) => {
    // page为点击搜索按钮是传递过来的第一页数据 翻页时也需要进行处理
    pageInfo.pageNum = page.pageNum
    pageInfo.pageSize = page.pageSize
    // 特殊需求：首次进入查立项页面不显示内容，要用户手动进行查询才进行数据返回
    // if (searchStore.searchType === "4" && enterSearchTypeByFourCount.value === 0) {
    //   enterSearchTypeByFourCount.value++
    //   return dataList.value = []
    // }
    if (isRest) {
      loading.value = true
      dataList.value = []
    }
    // 将子组件发射过来的查询参数保存
    queryParams.value = params
    await queryArticle({ ...params, searchType: searchStore.searchType, district: userInfo.value.parkAreaIds }, page).then((res: any) => {
      dataTotal.value = res.total
      // cut data
      dataList.value.push(...res.rows)
      newsData.value.push(...res.rows)
      if (searchStore.searchType === "1") {
        newsData.value = dataList.value.reduce((result, item) => {
          const date = item.sortTimeStr;

          // 查找是否已经有对应日期的分组
          const existingGroup = result.find((group: any) => group.label === date);

          if (existingGroup) {
            // 如果有，将当前项添加到该分组的列表中
            existingGroup.list.push(item);
          } else {
            // 如果没有，创建一个新的分组并添加到结果中
            result.push({ label: date, list: [item] });
          }

          return result;
        }, []);
      }
    }).finally(() => {
      loading.value = false
      // dataList.value.forEach(res=>{
      //   res.title =  hightLight(searchStore.searchValue,res.title)
      // })
    })
  },2000)

  // 重置pageInfo
  const resetPageInfo = () => {
    pageInfo.pageNum = 1
  }

  const goDetailPage = (id: string, searchType: any,name:String) => {
    // if(id==0){
    //   ElNotification({
    //     title: "无法查看",
    //     message: "查看失败",
    //     type: "error"
    //   });
    //   return
    // }
    window.open(`${location.origin}/detail?id=${id}&searchType=${searchType}&name=${name}`, "_blank")
  }

  // 加入vip
  const joinVip = () => {
    // 判断是否登录
    if (!jsCookie.get("token")) return zlDialog()

    goPage("/vipCenter")
  }

  // 跳转关于我们页面
  const goPage = (path: string) => {
    router.push(path)
  }


  /**
   * 首页资讯内容分类逻辑
   */
  const newsType = ref("1")
  const newsTabClick = () => {
  }



  /**
   * 底部加载逻辑
   */
  const bottomLoad = throttle(async () => {
    loading.value = true
    console.log('loading',loading)
    console.log('searchStore.searchType',searchStore.searchType)
    console.log('auth.value.iscCount',auth.value.iscCount)

    // 超过可查看限制直接返回false
    let limitCount = 0;
    switch (searchStore.searchType) {
      case "1":
        limitCount = auth.value.iscCount
        break;
      case "2":
        limitCount = auth.value.policyCount
        break;
      case "3":
        limitCount = auth.value.orgCount
        break;
      case "4":
        limitCount = auth.value.itemCount
        break;
    }
    loading.value = false
    if (((dataList.value.length >= limitCount && limitCount != -1) || dataList.value.length >= dataTotal.value) && searchStore.searchType !== "4") {
      console.log('======')
      return false
    }
    pageInfo.pageNum++
    await query(queryParams.value, false)
    loading.value = false
  },2000)

  /**
   * 聊天逻辑
   */
  const chatCardStatus = ref(false)

  const openChartCard = () => {
    // 判断是否登录
    if (!jsCookie.get("token")) return zlDialog()

    chatCardStatus.value = true
  }

  const openQAndA = () => {
    // 判断是否登录
    if (!jsCookie.get("token")) return zlDialog()
      router.push('/qAndA/index');
  }
  /**
   * banner
   */
  const bannerList = ref([])
  const getBanner = () => {
    getBannerData().then(res => {
      bannerList.value = res.data
    })
  }
  getBanner()




  const tableRowClassName = ({
    row,
    rowIndex
  }: {
    row: any;
    rowIndex: number;
  }) => {
    if (pageInfo.pageNum * pageInfo.pageSize - pageInfo.pageSize + rowIndex >= auth.value.itemCount) {
      return "hidden"
    }
  };

  const getHotInformation = (type:number)=>{
    hotInformation(type).then((res:any)=>{
      if(type==1){
        hotRepInformationList.value = res.data
      }else if(type==2){
        hotResInformationList.value = res.data
      }
    })
  }
  getHotInformation(1)
  getHotInformation(2)

  return {
    pageInfoChange,
    dataList,
    newsData,
    handleCardClick,
    query,
    dataTotal,
    pageInfo,
    loading,
    resetPageInfo,
    goDetailPage,
    joinVip,
    auth,
    goPage,
    newsType,
    newsTabClick,
    bottomLoad,
    chatCardStatus,
    openChartCard,
    bannerList,
    searchTypeInfos,
    tableRowClassName,
    vipType,
    hotResInformationList,
    hotRepInformationList,
    getDepHomeData,
    gather,
    openQAndA
  };
};
